package com.jiyi.easemob.view;


import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.controller.EaseUI;
import com.hyphenate.easeui.ui.EaseChatFragment;
import com.jiyi.activity.zone.ZoneQunZuInfoActivity;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.ClouldChatType;
import com.jiyi.event.HaoYouListEvent;
import com.jiyi.inteface.WebApi;
import com.swift.base.ActivityBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.utils.CustomDialogUtil;
import com.swift.widget.HaoYouMorePopInterface;
import com.swift.widget.HaoYouMorePopView;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class EasemobChatActivity extends ActivityBase implements HaoYouMorePopInterface{
	@BindView(R.id.tvBack)
	TextView tvBack;
	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.tvSearch)
	TextView tvSearch;

	public FragmentManager fm;
	//memberId
	private String memberId = "";
	// 环信群id或者用户id
	private String easemobgid = "";
	// 环信聊天类型
	private int easeMobChatType = 0;
	// 环信聊天fragment
	EaseChatFragment chatFragment;
	// 云上聊天类型
	private String cloudChatType = "";
	// 聊天对象名称
	private String id,name,remarkName;
	private String userpic,groupid;
	//是否指定群组
	private boolean isShareHuoDong;
	//指定群组对象
	private String zhiDingQunZu;
	//指定活动对象
	private String zhiDingHuoDong;
	//右上角的图标，根据群聊与私聊有做区分，群聊跳转到群信息，私聊有备注和删除的弹窗功能
	Drawable searchDraw;
	HaoYouMorePopView mHaoYouMorePopView;
	// 加载进度条
	Dialog dialog;
	// 备注好友
	final int REMARK = 1;
	// 退出群组
	final int EXIT = 2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_easemobchat);
		ButterKnife.bind(this);
		//获取聊天对象id
		id = getIntent().getStringExtra("id");
		//获取聊天对象名称
		name = getIntent().getStringExtra("name");
		//获取聊天对象备注名称
		remarkName = getIntent().getStringExtra("remark_name");
		//获取memberId
		memberId = getIntent().getStringExtra("memberId");
		// 获取easemobgid
		easemobgid = getIntent().getStringExtra("easemobgid");
		// 获取聊天类型
		easeMobChatType = getIntent().getIntExtra("easeMobChatType", 0);
		userpic = getIntent().getStringExtra(ClouldChatType.INTENT_USER_PIC);
		groupid = getIntent().getStringExtra(ClouldChatType.INTENT_Group_Id);
		//如果是私聊 显示右上角的图标
//		iv_top_right = (ImageView) findViewById(R.id.iv_top_right);
//		if (cloudChatType.equals(ClouldChatType.TYPE_SINGLE)) {
//			iv_top_right.setOnClickListener(this);
//    		iv_top_right.setImageResource(R.drawable.homepage_login_ico);
//		}
//		else {
//			iv_top_right.setVisibility(View.GONE);
//		}

		isShareHuoDong = getIntent().getBooleanExtra("isShareHuoDong", false);
		zhiDingQunZu = getIntent().getStringExtra("zhiDingQunZu");
		zhiDingHuoDong = getIntent().getStringExtra("zhiDingHuoDong");
		setTop();

		Boolean isNotifyClear = getIntent().getBooleanExtra(ClouldChatType.EASE_CHAT_ISNOTIFYCLEAR, false);
		//清除消息数量
		if (isNotifyClear) {
			EaseUI.getInstance().getNotifier().reset();
		}

		fm = getSupportFragmentManager();
		// 只當容器，主要內容已Fragment呈現
		initFragment();

	}

	@Override
	protected void onDestroy() {
		hideDialog(dialog);
		super.onDestroy();
	}

	/**
	 * @author: HYM
	 * @Title: setTop
	 * @Description: TODO(这里用一句话描述这个方法的作用)    void
	 * @date: 2017-6-29
	 */
	private void setTop() {
		tvBack.setText("");
		if (easeMobChatType == EaseConstant.CHATTYPE_GROUP) {
			searchDraw = getResources().getDrawable(R.mipmap.icon_zone_qunzu);
		}
		else {
			searchDraw = getResources().getDrawable(R.mipmap.icon_more);
			mHaoYouMorePopView = new HaoYouMorePopView(this, this);
		}

		searchDraw.setBounds(0, 0, searchDraw.getMinimumWidth(),searchDraw.getMinimumHeight());
		tvSearch.setCompoundDrawables(searchDraw, null, null, null);
		tvSearch.setText("");
		tvTitle.setText(TextUtils.isEmpty(remarkName) ? name : remarkName);
	}

	// 初始化Fragment
	public void initFragment() {
		// new出EaseChatFragment或其子类的实例
		chatFragment = new ChatFragment();
		// 传入参数
		Bundle args = new Bundle();
		// 设置聊天类型
		if (easeMobChatType == EaseConstant.CHATTYPE_GROUP) {
			args.putInt(EaseConstant.EXTRA_CHAT_TYPE,
					EaseConstant.CHATTYPE_GROUP);
		} else if (easeMobChatType == EaseConstant.CHATTYPE_SINGLE) {
			args.putInt(EaseConstant.EXTRA_CHAT_TYPE,
					EaseConstant.CHATTYPE_SINGLE);
		}

		// 设置用户或者群ID
		args.putString(EaseConstant.EXTRA_USER_ID, easemobgid);
		// 设置云上聊天消息类型
		args.putString(ClouldChatType.INTENT_MSG_TP, cloudChatType);
		args.putString(ClouldChatType.INTENT_USER_PIC, userpic);
		// 传入聊天对象id
		args.putString("id", id);
		// 传入聊天对象名称
		args.putString("name", name);
		args.putString(ClouldChatType.INTENT_Group_Id, groupid);
		args.putBoolean("isShareHuoDong", isShareHuoDong);
		args.putString("zhiDingQunZu", zhiDingQunZu);
		args.putString("zhiDingHuoDong", zhiDingHuoDong);
		chatFragment.setArguments(args);
		fm.beginTransaction().add(R.id.fragChat, chatFragment).commit();

	}

	@OnClick({ R.id.tvBack,R.id.tvSearch})
	public void onClick(View veiw) {
		Intent intent = null;
		switch (veiw.getId()) {
		case R.id.tvBack:
			finish();
			break;
		case R.id.tvSearch:
			if (easeMobChatType == EaseConstant.CHATTYPE_GROUP) {
				intent = new Intent(this,ZoneQunZuInfoActivity.class);
				intent.putExtra("groupId", id);
				startActivityForResult(intent, EXIT);
			}
			else {
				mHaoYouMorePopView.showPopWindow(tvSearch);
			}
			break;
		default:
			break;
		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		// 点击notification bar进入聊天页面，保证只有一个聊天页面
		String username = intent.getStringExtra("easemobgid");
		if (easemobgid.equals(username))
			super.onNewIntent(intent);
		else {
			finish();
			startActivity(intent);
		}

	}

	@Override
	public void onBackPressed() {
		chatFragment.onBackPressed();
	}

	@Override
	public void OnInfoListener() {
		mHaoYouMorePopView.hidePopWindow();
//		Intent intent = new Intent(this,ZoneHaoYouRemarkActivity.class);
//		intent.putExtra("id", id);
//		intent.putExtra("remark_name", remarkName);
//		startActivityForResult(intent, REMARK);
	}

	/**
	 * <p>Title: OnDeleteListener</p>
	 * <p>Description: </p>
	 * @see com.swift.widget.HaoYouMorePopInterface#OnDeleteListener()
	 */
	@Override
	public void OnDeleteListener() {
		mHaoYouMorePopView.hidePopWindow();
		final CustomDialogUtil ad = new CustomDialogUtil(
				this);
		ad.setTitle("提示");
		ad.setMessage("确定删除该好友吗？");
		ad.setPositiveButton("确定", new OnClickListener() {
			@Override
			public void onClick(View v) {
				doDelHaoYou(id);
				ad.dismiss();
			}
		});
		ad.setNegativeButton("取消", new OnClickListener() {
			@Override
			public void onClick(View v) {
				ad.dismiss();
			}
		});

	}

	/**
	 * <p>Title: OnShowListener</p>
	 * <p>Description: </p>
	 * @see com.swift.widget.HaoYouMorePopInterface#OnShowListener()
	 */
	@Override
	public void OnShowListener() {
		// TODO Auto-generated method stub

	}

	/**
	 * <p>Title: OnHideListener</p>
	 * <p>Description: </p>
	 * @see com.swift.widget.HaoYouMorePopInterface#OnHideListener()
	 */
	@Override
	public void OnHideListener() {
		// TODO Auto-generated method stub

	}

	void doDelHaoYou(String id) {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
		params.put("id", id);
		dialog = showDialog(dialog);
		VolleyRequest.StringRequestPost(this, WebApi.ZONE_HAOYOU_DEL, "", params,
				new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								ToastUtil.getInstances().showMsg(info);
								EventBus.getDefault()
										.post(new HaoYouListEvent(
												HaoYouListEvent.MY_HAOYOU_FRAGMENT));
								finish();
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							hideDialog(dialog);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						hideDialog(dialog);
						ToastUtil.getInstances().showMsg(R.string.err_http_response);
					}
				});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REMARK) {
			if (resultCode == RESULT_OK) {
				fm.beginTransaction().remove(chatFragment).commit();
				remarkName = data.getStringExtra("remark_name");
				tvTitle.setText(remarkName);
				initFragment();
			}
		}
		else if (requestCode == EXIT) {
			if (resultCode == RESULT_OK) {
				finish();
			}
		}
	}
}
